package com.fanqie.springboot2;

import com.fanqie.springboot2.scheduler.bean.SchedulerPO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledFuture;

/**
 * @author php
 * @date 2019/4/19
 */
@RestController
@Api(tags = "定时任务模块")
@RequestMapping("/scheduler")
public class SchedulerController {
    private final ThreadPoolTaskScheduler threadPoolTaskScheduler;
    private List<SchedulerPO> list = new ArrayList<>();

    /**
     * 默认启动一个定时任务
     *
     * @param threadPoolTaskScheduler threadPoolTaskScheduler
     */
    @Autowired
    public SchedulerController(ThreadPoolTaskScheduler threadPoolTaskScheduler) {
        this.threadPoolTaskScheduler = threadPoolTaskScheduler;
        //schedule有两个参数，Runnable task, Trigger trigger，task代表执行任务，trigger代表触发器
        String time = "*/10 * * * * ?";
        ScheduledFuture<?> future1 = this.threadPoolTaskScheduler.schedule(() -> {
            Thread thread = Thread.currentThread();
            System.out.println(thread.getName() + thread.getId() + ": 我还在活着");
        }, new CronTrigger(time));
        //保存到集合中，
        SchedulerPO schedulerPO = new SchedulerPO(1, "我是定时任务一", "创建", future1, time);
        list.add(schedulerPO);
    }


    @ApiOperation(value = "关闭定时任务", notes = "关闭定时任务")
    @PutMapping("/{id}/cancel")
    public void cancelById(@PathVariable int id) {
        list.forEach(schedulerPO -> {
            if (schedulerPO.getId() == id) {
                ScheduledFuture future = schedulerPO.getScheduledFuture();
                if (future != null) {
                    future.cancel(true);
                }
            }
        });
    }

    @ApiOperation(value = "查询所有定时任务", notes = "查询所有定时任务")
    @GetMapping("/all")
    public List all() {
        return list;
    }

    @ApiOperation(value = "添加定时任务", notes = "添加定时任务")
    @PostMapping("/add")
    public List add(@RequestBody SchedulerPO schedulerPO) {
        ScheduledFuture<?> future = this.threadPoolTaskScheduler.schedule(() -> {
            Thread thread = Thread.currentThread();
            System.out.println(thread.getName() + thread.getId() + ": 我还在活着");
        }, new CronTrigger(schedulerPO.getTime()));
        schedulerPO.setScheduledFuture(future);
        list.add(schedulerPO);
        return list;
    }
}
